import blueTool from '../../utils/bluetooth'
import { crc8, formatEcgData, formatOxiData, formatTmpData, getEcgWaveChart, parseEcgFileData, parseResponse, readFileData, startReadPkg, stopReadPkg } from '../../utils/checkme'
import { dataConversion, hexStr2Num } from '../../utils/number'
import api from '../../../api/index'
import dayjs from '../../../plugin/dayjs/index';
import * as echarts from '../../../components/ec-canvas/echarts';
//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;
var seriesDataArr1 = [];
var timeArr1 = [];
var chartPr = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatDatelx (date) {
	const year = date.substring(0, 4);
	const month = date.substring(4, 6);
	const day = date.substring(6, 8);
	const hours = date.substring(8, 10);
	const minutes = date.substring(10, 12);
	const seconds = date.substring(12, 14);
  
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i
    }
  }
  return -1
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    devices: [],
    lastecgResult:'',
    lasttime:'',
    shebeiicon: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/%E8%A1%80%E5%8E%8B.png',
    connected: false,
    result: null,
    newtime: '',
    label: '',
    deviceId: null,
    showDialog: false,
    ecgFiles: [],
    summary: {},
    showWaveEchart: true,
    ec1: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chartPr = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chartPr);
				return chartPr;
			}
    },
    ec: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				return chart;
			}
    },
    showec1: true,
    xAxisData1:[],
    yAxisData1:[],
    readFileItem: false,
		bleStatus: true,
  },
  ecgData: [],
  tmpData: [],
  oxiData: [],
  packageNum: 0,
  fileName: [],
  state: 0, // 0 start read 1 read content 2 end read
  bytesArray: [],
  fileData: [],
  allFileData: [],
  ecgChartData: [],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { 
    this.getloadlist()
    this.gethistrorylist()
    this.init()
  },
  gethistrorylist() {
    const actions = {
			data: {
				typecode: 'ecg',
        everyday: false
      },
			head: {
				firstresult: this.data.pageNum,
        maxresults: this.data.pageSize,
				bodytype: 'flat',
			}
		};
		api
			.post('/api/hxhealth/exams/records', actions)
			.then((res) => {
				console.log(res);
        // this.setData({
        //   list: res
        // });
        if (res.length > 0) {
          this.setData({
            newtime: res[0].time
          })
          if (res[0].devices && res[0].devices.length > 0) {
            const value = JSON.parse(res[0].devices[0].appendix)
            this.setData({
              lasttime: res[0].time, 
              lastecgResult: value.ecgResult
            })
            console.log('this.data.lasttime',value);
            this.getEchartData1({xAxisData: value.time,yAxisData: value.ecgData})
          }
        }
			});
	},
  getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'ecg',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----最新数据----', res);
				const array = res;
        if(res.length > 0) {
          this.setData({
            newtime: res[0].examtime
          });
        }
				
			});
	},
  savedevices() {
    let arr = this.waveChartOptions.yAxisData
    console.log(arr);
    arr = arr.filter(value => value !== null);
    console.log(arr);
    console.log(JSON.stringify(arr));
    const postData = {
      date: formatTime(),
      ecgData: arr,
      ecgResult: this.data.summary.result,
      time: this.waveChartOptions.xAxisData,
      unscramble: this.data.summary.explain
    }
    let time = this.data.ecgFiles[this.data.ecgFiles.length-1].fileName
    time = formatDatelx(time)
    console.log(time);
    if(time == this.data.lasttime) {
      console.log('无最新数据');
      wx.showToast({
        title: '无最新数据', //提示的内容,
        icon: 'none', //图标,
        duration: 2000, //延迟时间,
        mask: true, //显示透明蒙层，防止触摸穿透,
        success: res => {}
      });
      this.setData({
        showDialog: false
      })
      return
    }
		let data = {
			name: '心电监测',
			time: time,
			typecode: 'ecg',
			typename: '心电监测',
			devices: [
				{
					name: '心电监测',
					kind: 'ecg',
          appendix:JSON.stringify(postData),
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			
	},
  gohistorypage() {
    wx.navigateTo({
      url: `/electrocardiogram/pages/history/index`,
    })
  },
  onCancel() {
		this.setData({
			showDialog: false,
		})
		// 停止搜索
		blueTool.stopSearchBlueTooth()
	},
  bindEquipment(device) {
    console.log(device ,'绑定')
    this.setData({
      devices: [device]
    })
    this.setData({
			bindDeviceTextInfo: '连接设备中...'
		})
		this.setData({
			showDialog: true
		})
    const ds = device
    const deviceId = ds.deviceId
    blueTool.offOnChange()
    blueTool.stopSearchBlueTooth().then(() => {
      blueTool.createDevice({
        deviceId
      }).then((res) => {
        this.setData({
          deviceId
        })
        blueTool.getMacDir(res, bytesArray => {
          this.bytesArray = this.bytesArray.concat(bytesArray)
          this.parseFile(this.bytesArray)
        })
        setTimeout(() => {
          this.setData({
            bindDeviceTextInfo: '链接设备成功，正在同步数据'
          })
          this.setData({
            readFileItem: false
          })
          this.readEcg()
        }, 1000)
      }).catch(() => {
      })
    })
  },
  parseFile(bytesArray) {
    for (let i = 0; i < bytesArray.length - 7; i++) {
      if (bytesArray[i] !== '55' || bytesArray[i + 1] != "00" || bytesArray[i + 2].toLocaleLowerCase() !== 'ff') {
        continue
      }

      const len = hexStr2Num(dataConversion(bytesArray.slice(5, 7).join('')))
      if (i + 8 + len > bytesArray.length) {
        continue
      }

      const temp = bytesArray.slice(i, i + 8 + len)
      if (parseInt(temp[temp.length - 1], 16) === parseInt(crc8(temp), 16)) {
        const res = parseResponse(temp)
        if (this.state === 0) {
          this.state = 1
          this.bytesArray = []
          this.fileData = []
          const buffSize = hexStr2Num(res.contentStr)
          this.packageNumMax = Math.floor(buffSize / 512)
          console.log(this.packageNumMax,'------------lzm111----------');
          if (this.packageNumMax == 0 && this.data.readFileItem) {
            wx.showToast({
              title: '无数据111', //提示的内容,
              icon: 'none', //图标,
              duration: 2000, //延迟时间,
              mask: true, //显示透明蒙层，防止触摸穿透,
              success: res => {}
            });
            this.setData({
              showDialog: false
            })
            return
          }
          this.readContent()
        } else if (this.state === 1) {
          this.fileData = this.fileData.concat(res.content)
          if (this.packageNumMax == 0) {
            this.parseFileByFileType()
            this.stopReadPkg()
          } else if (this.packageNumMax < this.packageNum) {
            this.parseFileByFileType()
            this.stopReadPkg()
          } else {
            setTimeout(() => {
              this.fileData = []
              this.bytesArray = []
              this.packageNum++
              this.readContent()
            }, 500)
          }
        }
      }
    }
    if (this.fileData.length > 0 && this.data.readFileItem) {
      console.log(this.fileData, 'HHHHHHHHHHH')
      this.allFileData = this.allFileData.concat(this.fileData)
    }
  },
  startReadPkg() {
    this.state = 0
    this.contentData = []
    this.packageNum = 0
    this.bytesArray = []

    startReadPkg({
      deviceId: this.data.deviceId,
      fileName: this.fileName
    })
  },

  readContent() {
    readFileData({
      deviceId: this.data.deviceId,
      packageNum: this.packageNum
    })
  },

  stopReadPkg() {
    this.state = 2
    stopReadPkg({
      deviceId: this.data.deviceId
    })
  },

  parseFileByFileType() {
    console.log(this.fileType, 'this.fileType')
    switch (this.fileType) {
      case 'ecg-list':
        this.parseEcgList()
        break;

      case 'ecg-item':
        this.parseEcgItem()
        break

      case 'oxi-list':
        this.parseOxiList()
        break

      case 'tmp-list':
        this.parseTmpList()
        break

      default:
        break;
    }
  },

  readEcg(e) {
    this.fileName = 'ecg.dat'
    this.fileType = 'ecg-list'
    this.ecgData = []
    this.startReadPkg()
  },

  async readEcgFileItem(e) {
    this.setData({
      readFileItem: true
    })
    this.fileType = 'ecg-item'
    const ds = e
    const fileName = ds.fileName
    this.fileName = fileName

    this.startReadPkg()
  },

  getEchartData(linedata) {
    // console.log({values: Array(2), times: Array(2)});
		seriesDataArr = [
			{
				name: '心率变化趋势',
        type: 'line',
        symbol: 'circle',
				stack: 'Total',
				smooth: true,
        data: linedata.yAxisData,
        lineStyle: {
          width: 1,
          shadowColor: 'rgba(0,0,0,0.1)',
          shadowBlur: 10,
          shadowOffsetY: 8
        },
			}
    ];
    var length = linedata.yAxisData.length; // 例如，长度为5
    // 创建并填充数组
    var arr = [];
    for (var i = 1; i <= length; i++) {
        arr.push(i);
    }
    console.log(arr);
    timeArr = arr;
		this.runColumncCanva();
  },
  // 绘制图表
	runColumncCanva() {
		var option = {
			title: {
				// text: '次/分',
				textStyle: {
					fontSize: 9,
					color: '#666666'
				}
			},
			color: [ '#37A2DA' ],
			legend: {
				data: [ '心率变化趋势' ],
				icon: 'circle',
				left: 0,
				itemWidth: 9,
				// itemStyle: {
				//     color: '#5BBF70'
				// },
				textStyle: {
				    color: '#333333',
				    fontSize: 13
				}
			},
      grid: {
				left: '0%',
				right: '1%',
				bottom: '20%',
				top: '0%',
				containLabel: true,
				show: false
			},
			tooltip: {
				show: false,
				trigger: 'axis'
			},
			xAxis: {
        show: true,
				type: 'category',
				boundaryGap: false,
				data: timeArr,
				axisLabel: {
          show: false,
					fontSize: 12,
					rotate: 0 //倾斜度 -90 至 90 默认为0
        },
        axisLine: {
          show: false,
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: "#D4DFF5",
          },
        },
			},
			yAxis: {
				type: 'value',
        show: true,
        axisLine: {
          show: false,
        },
				splitLine: {
          lineStyle: {
            color: '#D4DFF5',
            type: "dashed"
          },
        },
				axisLabel: {
          show: false,
					fontSize: 16
				}
      },
      dataZoom: [{ // 这是dataZoom组件
        type: 'slider', // 这里可以选择你需要的dataZoom类型
        start: 0, // 默认数据初始选择范围为10%
        end: 16 // 默认数据结束选择范围为100%
    }],
			series: seriesDataArr
		};
    //这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
    console.log('-------chart------------------chart---------------------chart-------------------------------------------');
    console.log(chart);
		if (chart) {
			chart.setOption(option);
			this.setData({
				show: true
			});
		}
	},
  getEchartData1(linedata) {
    console.log({values: Array(2), times: Array(2)});
    console.log(linedata,'linedata')
		seriesDataArr1 = [
			{
				name: '心率变化趋势',
        type: 'line',
        symbol: 'none',
				stack: 'Total',
				smooth: true,
        data: linedata.yAxisData,
        lineStyle: {
          width: 1,
          shadowColor: 'rgba(0,0,0,0.1)',
          shadowBlur: 10,
          shadowOffsetY: 8
        },
			}
    ];
    var length = linedata.yAxisData.length; // 例如，长度为5
    // 创建并填充数组
    var arr = [];
    for (var i = 1; i <= length; i++) {
        arr.push(i);
    }
    console.log(arr);
    timeArr1 = arr;
    console.log(seriesDataArr1);
		this.runColumncCanva1();
  },
  // 绘制图表
	runColumncCanva1() {
    console.log(seriesDataArr1);
    console.log(timeArr1);
		var option = {
			title: {
				// text: '次/分',
				textStyle: {
					fontSize: 9,
					color: '#666666'
				}
			},
			color: [ '#37A2DA' ],
			legend: {
        show: false,
				data: [ '心率变化趋势' ],
				icon: 'circle',
				left: 0,
				itemWidth: 9,
				// itemStyle: {
				//     color: '#5BBF70'
				// },
				textStyle: {
				    color: '#333333',
				    fontSize: 13
				}
			},
			grid: {
				left: '0%',
				right: '1%',
				bottom: '20%',
				top: '0%',
				containLabel: true,
				show: false
			},

			tooltip: {
				show: false,
				trigger: 'axis'
			},
			xAxis: {
        show: true,
				type: 'category',
				boundaryGap: false,
				data: timeArr1,
				axisLabel: {
          show: false,
					fontSize: 12,
					rotate: 0 //倾斜度 -90 至 90 默认为0
        },
        axisLine: {
          show: false,
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: "#D4DFF5",
          },
        },
			},
			yAxis: {
				type: 'value',
        show: true,
        axisLine: {
          show: false,
        },
				splitLine: {
          lineStyle: {
            color: '#D4DFF5',
            type: "dashed"
          },
        },
				axisLabel: {
          show: false,
					fontSize: 16
				}
      },
      series: seriesDataArr1,
      dataZoom: [{ // 这是dataZoom组件
        type: 'slider', // 这里可以选择你需要的dataZoom类型
        start: 0, // 默认数据初始选择范围为10%
        end: 16 // 默认数据结束选择范围为100%
    }]
		};
    //这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
    console.log(chartPr);
    if (chartPr) {
      chartPr.setOption(option);
		}
	},
  gobindEle() {
    wx.navigateTo({
			url: `/electrocardiogram/pages/measurement/index?bleStatus=${this.data.bleStatus}`
		});
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  async get() {
    this.setData({
      bindDevice: []
    })
    try {
      this.setData({
        loading: true
      })
      const res = await api.post('/api/user/storage/get', {
        data: {
          'key': 'devicelist'
        }
      })
      if (res[0].value) {
        var array = JSON.parse(res[0].value)
        const listValue = array.filter(item => item.name === 'electro')
        if (listValue.length > 0 && listValue[0].devicelist.length > 0) {
          this.setData({
            bindDevice: listValue[0].devicelist
          })
          this.bindEquipment(listValue[0].devicelist[0])
        }
      }
      this.setData({
        loading: false
      })
    } catch (e) {
      console.log('get->', e)
      return null
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },
  doBluetoothAdapterStateChange() {
		console.log('获取蓝牙的状态')
		wx.onBluetoothAdapterStateChange((res) => {
			console.log('蓝牙状态', res)
			if (res.available) {
				this.setData({
					bleStatus: true
				})
			} else {
				this.setData({
					bleStatus: false
				})
			}
		})
	},
  init() {
    blueTool.initBlueTooth().then(res => {
      this.setData({
				bleStatus: true,
			})
      this.doBluetoothAdapterStateChange()
      this.get()
    }).catch(error => {
      this.doBluetoothAdapterStateChange()
      this.setData({
        bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙',
				bleStatus: false,
      })
      this.setData({
        showDialog: true
      })
      console.log(error, 'error')
    })
},
parseEcgList() {
    const data = formatEcgData(this.fileData)
    console.log(data,'---------lzmdata----000----------');
    if( data.length > 0 ) {
        this.setData({
            ecgFiles: data
        }) 
        console.log(data); 
        console.log(data[data.length-1], 'readEcgFileItem');
        console.log(this.data.lasttime);
        if(formatDatelx(data[data.length-1].fileName) == this.data.lasttime) {
          wx.showToast({
            title: '暂无数据', //提示的内容,
            icon: 'none', //图标,
            duration: 2000, //延迟时间,
            mask: true, //显示透明蒙层，防止触摸穿透,
            success: res => {}
          });
          this.setData({
           showDialog: false
         })
         return
        }
        setTimeout(() => {
          this.readEcgFileItem(data[data.length-1])
        }, 1000)
    } 
    else {
       wx.showToast({
         title: '暂无数据', //提示的内容,
         icon: 'none', //图标,
         duration: 2000, //延迟时间,
         mask: true, //显示透明蒙层，防止触摸穿透,
         success: res => {}
       });
       this.setData({
        showDialog: false
      })
    }
    
},
parseEcgItem() {
  const ecgItemData = parseEcgFileData(this.allFileData)
  console.log(ecgItemData.waveList, 'ecgItemData')
  const date = {
    xAxisData: [],
    yAxisData: ecgItemData.waveList
  }
  this.getEchartData(date)
  this.waveChartOptions = date 
    console.log(ecgItemData, 'ecgItemData')
    this.setData({
        summary: ecgItemData.summary,
    })
    this.setData({
      bindDeviceTextInfo: '同步数据成功'
    })
    setTimeout(() => {
      this.setData({
        showDialog: false
      })
    }, 500);
    this.savedevices()
},

parseOxiList() {
    const data = formatOxiData(this.fileData)
    if(data) {
        this.setData({
            label: '脉指数据',
            result: JSON.stringify(data, null, 4)
        })
    }
    console.log(this.data.result,'resul2')

},

parseTmpList() {
    const data = formatTmpData(this.fileData)

    if(data) {
        this.setData({
            label: '体温数据',
            result: JSON.stringify(data, null, 4)
        })
    }
    console.log(this.data.result,'resul3')

},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('unload', this.data.deviceId)
    if (this.data.deviceId) {
      blueTool.closeDevice(this.data.deviceId)
        .then(() => {
            this.setData({
                connected: false,
                ecgData: [],
                devices: []
            })
        })
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  }
})

